package com.ytkj.tradeserver.utils;

import com.ytkj.tradeserver.constant.ComConstants;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;

/**
 * Created by Administrator on 2017/4/23.
 */
public class HttpOptionUtils {

    public static String requestData(String url,String dataStr,String requestType){
        System.out.println( " url : "  + url);
        System.out.println( " dataStr : "  + dataStr);
        String result = "";
        BufferedReader in = null;
        OutputStreamWriter osw = null;
        PrintWriter out = null;
        URL realUrl = null;
        try {
            realUrl =  new URL(url);
            if(ComConstants.REQUESTTYPE_GET.equals(requestType)){
                realUrl =  new URL(url+"/"+dataStr);
            }
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            connection.setConnectTimeout(5*1000);

            if(ComConstants.REQUESTTYPE_POST.equals(requestType)){
                // 发送POST请求必须设置如下两行
                connection.setDoOutput(true);
                connection.setDoInput(true);
                // 获取URLConnection对象对应的输出流
                out = new PrintWriter(connection.getOutputStream());
                // 发送请求参数
                out.print(dataStr);
                // flush输出流的缓冲
                out.flush();
            }else{
                // 建立实际的连接
                connection.connect();
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            System.out.println( "app return content: " + result );
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

}
